<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <a-form :model="queryParams" ref="queryRef" layout="inline" v-show="showSearch">
      <a-form-item label="赛段名称" name="stageName">
        <a-select
          v-model:value="queryParams.stageName"
          placeholder="请选择赛段名称"
          allow-clear
          style="width: 120px"
          @keyup.enter="handleQuery"
        >
          <a-select-option
            v-for="item in raceOptions"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="赛车" name="saiche">
        <a-select
          v-model:value="queryParams.saiche"
          placeholder="请选择赛车"
          allow-clear
          style="width: 120px"
          @change="onQuerySaicheChange"
          @keyup.enter="handleQuery"
        >
          <a-select-option
            v-for="item in raceOptions2"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="赛车手" name="racerName">
        <a-select
          v-model:value="queryParams.racerName"
          placeholder="请选择赛车手"
          allow-clear
          style="width: 120px"
        >
          <a-select-option
            v-for="item in raceOptions3"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="handleQuery">
          <template #icon><SearchOutlined /></template>
          搜索
        </a-button>
        <a-button @click="resetQuery" style="margin-left: 8px">
          <template #icon><ReloadOutlined /></template>
          重置
        </a-button>
      </a-form-item>
    </a-form>

    <!-- 操作按钮 -->
    <a-row :gutter="10" class="mb8">
      <a-col :span="1.5">
        <a-button type="primary" @click="handleAdd">
          <template #icon><PlusOutlined /></template>
          新增
        </a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button type="default" :disabled="single" @click="handleUpdate">
          <template #icon><EditOutlined /></template>
          修改
        </a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button type="primary" danger :disabled="multiple" @click="handleDelete">
          <template #icon><DeleteOutlined /></template>
          删除
        </a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button type="default" @click="handleExport">
          <template #icon><DownloadOutlined /></template>
          导出
        </a-button>
      </a-col>
<!--      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
    </a-row>

    <!-- 表格 -->
    <a-table 
      :loading="loading" 
      :data-source="stageInfoList" 
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: handleSelectionChange }"
      :pagination="false"
      row-key="id"
    >
      <a-table-column title="赛段名称" data-index="stageName" align="center" />
      <a-table-column title="赛车" data-index="saiche" align="center" />
      <a-table-column title="赛车手" data-index="racerName" align="center" />
      <a-table-column title="排名" data-index="ranking" align="center" />
      <a-table-column title="积分" data-index="points" align="center" />
      <a-table-column title="完成时间" data-index="wanchengshijian" align="center" :width="180">
        <template #default="{ record }">
          <span>{{ parseTime(record.wanchengshijian, '{y}-{m}-{d}') }}</span>
        </template>
      </a-table-column>
      <a-table-column title="操作" align="center" class-name="small-padding fixed-width">
        <template #default="{ record }">
          <a-space>
            <a-button type="link" @click="handleUpdate(record)">
              <template #icon><EditOutlined /></template>
              修改
            </a-button>
            <a-button type="link" danger @click="handleDelete(record)">
              <template #icon><DeleteOutlined /></template>
              删除
            </a-button>
          </a-space>
        </template>
      </a-table-column>
    </a-table>

    <!-- 分页 -->
    <div class="table-pagination" style="margin-top: 16px; text-align: right" v-show="total > 0">
      <a-pagination
        :total="total"
        :current="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        @change="handlePageChange"
        @showSizeChange="handlePageSizeChange"
        show-size-changer
        :show-total="(total) => `共 ${total} 条`"
      />
    </div>

    <!-- 弹窗：新增/修改赛段排名 -->
    <a-modal :title="title" v-model:open="open" width="500px" :confirm-loading="submitLoading">
      <a-form ref="stageInfoRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="赛段名称" name="stageName">
          <a-select v-model:value="form.stageName" placeholder="请选择赛段名称" allow-clear>
            <a-select-option 
              v-for="item in raceOptions" 
              :key="item.value" 
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="赛车" name="saiche">
          <a-select v-model:value="form.saiche" placeholder="请选择赛车车牌" allow-clear @change="onFormSaicheChange">
            <a-select-option 
              v-for="item in raceOptions2" 
              :key="item.value" 
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="赛车手" name="racerName">
          <a-select v-model:value="form.racerName" placeholder="请选择赛车手" allow-clear>
            <a-select-option 
              v-for="item in raceOptions3" 
              :key="item.value" 
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="排名" name="ranking">
          <a-input v-model:value="form.ranking" placeholder="请输入排名" />
        </a-form-item>
        <a-form-item label="积分" name="points">
          <a-input v-model:value="form.points" placeholder="请输入积分" />
        </a-form-item>
        <a-form-item label="完成时间" name="wanchengshijian">
          <a-date-picker 
            v-model:value="form.wanchengshijian" 
            value-format="YYYY-MM-DD" 
            placeholder="请选择完成时间" 
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button type="primary" @click="submitForm" :loading="submitLoading">确 定</a-button>
        <a-button @click="cancel">取 消</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, getCurrentInstance } from 'vue';
import { message, Modal } from 'ant-design-vue';
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  DownloadOutlined
} from '@ant-design/icons-vue';
import { listStageInfo, getStageInfo, delStageInfo, addStageInfo, updateStageInfo,
         listAllSaiduan, listAllSaiche, listAllSaicheshou } from '/@/api/offroad/stageSys/stageInfo';
const parseTime = (time, format) => {
  if (!time) return '';
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return format.replace('{y}', year).replace('{m}', month).replace('{d}', day);
};
const { proxy } = getCurrentInstance();

// 数据与状态
const stageInfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const submitLoading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const selectedRowKeys = ref([]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    stageName: null,
    saiche: null,
    racerName: null,
    ranking: null,
    points: null,
    wanchengshijian: null
  },
  form: {
    id: null,
    stageName: null,
    saiche: null,
    racerName: null,
    ranking: null,
    points: null,
    wanchengshijian: null
  },
  rules: {
    stageName: [{ required: true, message: '赛段名称不能为空', trigger: 'blur' }],
    racerName: [{ required: true, message: '赛车手不能为空', trigger: 'blur' }],
    ranking:   [{ required: true, message: '排名不能为空', trigger: 'blur' }]
  }
});
const { queryParams, form, rules } = toRefs(data);

// 下拉列表数据
const raceOptions = ref([]);
const raceOptions2 = ref([]);
const raceOptions3 = ref([]);

// 获取列表
function getList() {
  loading.value = true;
  listStageInfo(queryParams.value).then(res => {
    stageInfoList.value = res.data.list;
    total.value = res.data.total;
    loading.value = false;
  });
}

// 重置查询表单
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    stageId: null,
    racerId: null,
    vehicleId: null,
    ranking: null,
    stageTime: null,
    totalTime: null,
    penalty: null,
    status: null,
  };
  getList();
}

// 处理查询按钮
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 监听查询区赛车变化
function onQuerySaicheChange(val) {
  queryParams.value.racerName = null;
  raceOptions3.value = [];
  if (val) listDrivers(val);
}

// 监听弹窗区赛车变化
function onFormSaicheChange(val) {
  form.value.racerName = null;
  raceOptions3.value = [];
  if (val) listDrivers(val);
}

// 拉取赛段、赛车、赛车手
function listStages() { listAllSaiduan().then(r=> raceOptions.value = r.data.map(i=>({ value:i, label:i }))); }
function listCars()   { listAllSaiche().then(r=> raceOptions2.value = r.data.map(i=>({ value:i, label:i }))); }
function listDrivers(saiche) { listAllSaicheshou(saiche).then(r=> raceOptions3.value = r.data.map(i=>({ value:i, label:i }))); }

// 弹窗操作
function handleAdd() {
  if (proxy.$refs.stageInfoRef) {
    proxy.$refs.stageInfoRef.resetFields();
  }
  open.value = true;
  title.value = '添加赛段排名';
}
function handleUpdate(row) {
  if (proxy.$refs.stageInfoRef) {
    proxy.$refs.stageInfoRef.resetFields();
  }
  const id = row.id || ids.value;
  getStageInfo(id).then(res => {
    Object.assign(form.value, res.data);
    open.value = true;
    title.value = '修改赛段排名';
  });
}

// 删除
function handleDelete(row) {
  const id = row?.id || ids.value;
  Modal.confirm({
    title: '确认删除',
    content: `是否确认删除编号“${id}”？`,
    onOk() {
      return delStageInfo(id).then(()=> {
        message.success('删除成功');
        getList();
      });
    }
  });
}

// 提交表单
function submitForm() {
  proxy.$refs.stageInfoRef.validate().then(() => {
    submitLoading.value = true;
    const action = form.value.id ? updateStageInfo : addStageInfo;
    action(form.value).then(()=> {
      message.success(form.value.id ? '修改成功' : '新增成功');
      open.value = false;
      getList();
    }).finally(() => {
      submitLoading.value = false;
    });
  });
}

// 表格多选
function handleSelectionChange(selectedKeys, selectedRows) {
  selectedRowKeys.value = selectedKeys;
  ids.value = selectedRows.map(i=>i.id);
  single.value = selectedRows.length !== 1;
  multiple.value = !selectedRows.length;
}

// 分页页码变化
function handlePageChange(page, pageSize) {
  queryParams.value.pageNum = page;
  queryParams.value.pageSize = pageSize;
  getList();
}

// 分页大小变化
function handlePageSizeChange(current, size) {
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = size;
  getList();
}

// 导出
function handleExport() {
  proxy.download('stageSys/stageInfo/export', {...queryParams.value}, `stageInfo_${Date.now()}.xlsx`);
}

// 取消按钮
function cancel() {
  open.value = false;
  if (proxy.$refs.stageInfoRef) {
    proxy.$refs.stageInfoRef.resetFields();
  }
}

onMounted(() => {
  listStages(); listCars();
  // 初次不拉drivers
  getList();
});
</script>

<style scoped>
.app-container { padding: 16px; }
.mb8 { margin-bottom: 8px; }
.small-padding { padding: 4px; }
.fixed-width { width: 120px; }
</style>